//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package board_dao

import (
	"context"
	"time"

	"gitcode.com/eteam/api-server/dao/common"
	"gitcode.com/eteam/proto-gen-go.git/board_member_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type InviteInfoDbItem struct {
	InviteCode string `bson:"_id"`
	BoardId    string `bson:"boardId"`
	GenTime    int64  `bson:"genTime"`
	ExpireTime int64  `bson:"expireTime"`
	TtlHour    uint32 `bson:"ttlHour"`
}

func (item *InviteInfoDbItem) ToInviteInfo() *board_member_api.InviteInfo {
	return &board_member_api.InviteInfo{
		InviteCode: item.InviteCode,
		BoardId:    item.BoardId,
		GenTime:    item.GenTime,
		ExpireTime: item.ExpireTime,
		TtlHour:    item.TtlHour,
	}
}

type _InviteDao struct {
	mc *mongo.Collection
}

func newInviteDao(db *mongo.Database) (*_InviteDao, error) {
	mc := db.Collection(common.DB_NS_BOARD + "invite")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"boardId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_InviteDao{mc: mc}, nil
}

func (db *_InviteDao) Insert(ctx context.Context, dbItem *InviteInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_InviteDao) Exist(ctx context.Context, inviteCode string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": inviteCode})
	return count > 0, err
}

func (db *_InviteDao) Get(ctx context.Context, inviteCode string) (*InviteInfoDbItem, error) {
	retItem := &InviteInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": inviteCode}).Decode(retItem)
	return retItem, err
}

func (db *_InviteDao) Remove(ctx context.Context, boardId, inviteCode string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": inviteCode, "boardId": boardId})
	return err
}

func (db *_InviteDao) RemoveExpire(ctx context.Context, boardId string) error {
	nowTime := time.Now().UnixMilli()
	_, err := db.mc.DeleteMany(ctx, bson.M{"boardId": boardId, "expireTime": bson.M{"$lte": nowTime}})
	return err
}

func (db *_InviteDao) ListByBoard(ctx context.Context, boardId string) ([]*InviteInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"boardId": boardId}, options.Find().SetSort(bson.M{"genTime": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*InviteInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
